#include "uart.h"
struct termios newtio,oldtio;
int uart_fd = -1;
int recive_cont,recive_flag;
char recive_buf[30];

/* 设置串口参数 set_opt(uart_fd, 115200, 8, 'N', 1) */
int set_opt(int uart_fd, int nSpeed, int nBits, char nEvent, int nStop)
{
    //获得终端的属性
    if(tcgetattr(uart_fd, &oldtio) != 0) {
        perror("Setup");
        return -1;
    }
    bzero(&newtio, sizeof(newtio));
    cfmakeraw(&newtio);
    /* 先使能相关的操作 */
	newtio.c_cflag |= CLOCAL | CREAD; 
	newtio.c_cflag &= ~CSIZE;

    newtio.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/
	newtio.c_oflag  &= ~OPOST;   /*Output*/

    switch(nBits) {
        case 7:
            newtio.c_cflag |= CS7;
        break;
        case 8:
            newtio.c_cflag |= CS8;
        break;;
        default:
            newtio.c_cflag |= CS8;
        break;
    }

    switch(nEvent) {
        case 'O':
            newtio.c_cflag |= PARENB;
            newtio.c_cflag |= PARODD;
            newtio.c_iflag |= (INPCK | ISTRIP);
        break;
        case 'E': 
            newtio.c_iflag |= (INPCK | ISTRIP);
            newtio.c_cflag |= PARENB;
            newtio.c_cflag &= ~PARODD;
        break;
        case 'N': 
            newtio.c_cflag &= ~PARENB;
        break;
    }

    switch(nSpeed) {
        case 2400:
            cfsetspeed(&newtio, B2400);
        break;
        case 4800:
            cfsetspeed(&newtio, B4800);
        break;
        case 9600:
            cfsetspeed(&newtio, B9600);
        break;
        case 115200:
            cfsetspeed(&newtio, B115200);
        break;
        default:
            cfsetspeed(&newtio, B9600);
	    break;
    }

    if(nStop == 1)
		newtio.c_cflag &= ~CSTOPB;
	else if (nStop == 2)
		newtio.c_cflag |= CSTOPB;

	newtio.c_cc[VMIN]  = 0;     /* 读数据时的最小字节数: 没读到这些数据我就不返回! */
	newtio.c_cc[VTIME] = 0;     /* 等待第1个数据的时间: */
      
    tcflush(uart_fd,TCIFLUSH);

    /* 把修改好的参数，设置进终端设备中 */
    if((tcsetattr(uart_fd,TCSANOW,&newtio))!=0) {
		perror("com set error");
		return -1;
	}
	return 0;
}

/* 打开串口设备 */
int open_uart(void)
{
    int ret = -1;
    uart_fd = open("/dev/ttySTM1", O_RDWR | O_NOCTTY);
    if(0 > uart_fd) {
        perror("open /dev/ttySTM1 err!\n");
        return -1;
    }
    ret = set_opt(uart_fd, 115200, 8, 'N', 1);
    if(ret) {
        printf("set_opt err!\n");
        return -1;
    }
    return ret;
}
